// 事件处理
import { keepDecimal } from "@/utils/index";
export function initEvents(vm) {
  return {
    // 触发模型筛选
    handleFindImgItems(params) {
      vm.requestgetModel(params, "model");
    },
    // 处理对象移动事件
    handleObjectMoving(options) {
      const object = options.target;
      vm.updateArrowAndBorderPosition(object);
    },
    // 处理对象旋转事件
    handleObjectRotating(options) {
      const object = options.target;
      vm.updateArrowAndBorderPosition(object);
    },
    throttledRender() {
      if (!vm.isRendering) {
        vm.isRendering = true;
        requestAnimationFrame(() => {
          vm.canvas.requestRenderAll();
          vm.isRendering = false;
        });
      }
    },
    // 处理滚轮缩放
    handleMouseWheel(options) {
      options.e.preventDefault();
      options.e.stopPropagation();

      // const now = Date.now();
      // if (now - vm.lastRenderTime < vm.renderThrottle) return;
      // vm.lastRenderTime = now;

      const delta = options.e.deltaY;
      const zoomFactor = 0.05;
      const canvas = vm.canvas;

      // 获取当前视口变换状态
      const currentZoom = canvas.getZoom();
      const viewportTransform = canvas.viewportTransform.slice();

      // 计算新缩放比例
      let newZoom =
        delta > 0
          ? currentZoom * (1 - zoomFactor)
          : currentZoom * (1 + zoomFactor);

      // 限制缩放范围
      newZoom = Math.min(
        Math.max(newZoom, vm.initialZoom * vm.minZoom),
        vm.initialZoom * vm.maxZoom
      );

      // 获取鼠标在画布上的实际坐标（不受视口变换影响）
      const pointer = canvas.getPointer(options.e);
      const mousePoint = new fabric.Point(pointer.x, pointer.y);

      // 计算缩放后的视口变换
      const zoomRatio = newZoom / currentZoom;
      const newTransform = fabric.util.multiplyTransformMatrices(
        canvas.viewportTransform,
        [
          zoomRatio,
          0,
          0,
          zoomRatio,
          mousePoint.x * (1 - zoomRatio),
          mousePoint.y * (1 - zoomRatio),
        ]
      );

      // 应用新的视口变换
      canvas.setViewportTransform(newTransform);
      canvas.setZoom(newZoom); // 显式设置缩放比例

      // 更新所有对象坐标
      vm.updateAllObjectsCoords();
      // canvas.requestRenderAll();
      vm.throttledRender();
    },
    // 鼠标按下事件
    handleCanvasMouseDown(options) {
      // 优先处理图片放置
      if (vm.selectedImg) {
        vm.wayPlaceImage(options.e, "selectedImg");
        return;
      }
      if (vm.selectedPosition) {
        vm.wayPlaceImage(options.e, "selectedPosition");
        return;
      }
      // 对于可选中的对象，保持原有选中逻辑
      if (options.target && options.target.selectable) {
        return; // 让Fabric.js默认处理选中逻辑
      }
      // 拖拽逻辑 - 对于不可选中的对象或空白区域，需要按住Ctrl键才能拖动
      if (options.e.ctrlKey) {
        vm.isDragging = true;
        vm.canvas.defaultCursor = "grab";
        vm.lastPosX = options.e.clientX;
        vm.lastPosY = options.e.clientY;
      }
      // if (
      //   (!options.target || !options.target.selectable) &&
      //   options.e.ctrlKey
      // ) {
      //   vm.isDragging = true;
      //   vm.canvas.defaultCursor = "grab";
      //   vm.lastPosX = options.e.clientX;
      //   vm.lastPosY = options.e.clientY;
      // }
      // if (!options.target && !vm.isFunctionalKeyPressed(options.e)) {
      //   vm.isDragging = true;
      //   vm.canvas.defaultCursor = "grab";
      //   vm.lastPosX = options.e.clientX;
      //   vm.lastPosY = options.e.clientY;
      // }
    },
    // 鼠标移动事件
    handleMouseMove(options) {
      if (vm.isDragging) {
        // const now = Date.now();
        // if (now - vm.lastRenderTime < vm.renderThrottle) return;
        // vm.lastRenderTime = now;
        vm.canvas.defaultCursor = "grabbing";
        const deltaX = options.e.clientX - vm.lastPosX;
        const deltaY = options.e.clientY - vm.lastPosY;
        // 获取当前视口变换参数
        const vpt = vm.canvas.viewportTransform;
        vpt[4] += deltaX;
        vpt[5] += deltaY;
        // 更新所有对象的坐标
        vm.updateAllObjectsCoords();
        vm.lastPosX = options.e.clientX;
        vm.lastPosY = options.e.clientY;
        // vm.canvas.requestRenderAll();
        vm.throttledRender();
      } else {
        // 获取鼠标位置下的对象
        const pointer = vm.canvas.getPointer(options.e);
        const hoveredFabricObj = vm.canvas.findTarget(pointer);
        if (hoveredFabricObj) {
          // 在allObjects中查找对应的数据对象
          const hoverObject = vm.allObjects.find(
            (obj) => obj.fabricObject === hoveredFabricObj
          );
          if (hoverObject) {
            vm.hoverObject = hoverObject;
            // 这里可以访问dataObj的所有自定义属性
            // 例如: dataObj.posId, dataObj.text 等
            // console.log('找到对应的数据对象:', vm.hoverObject);
          }
        } else {
          vm.hoverObject = null;
        }
      }
    },
    // 鼠标释放事件
    handleMouseUp() {
      vm.isDragging = false;
      vm.canvas.defaultCursor = "default";
      // 更新所有对象坐标
      vm.updateAllObjectsCoords();
      // vm.canvas.requestRenderAll();
      vm.throttledRender();
    },
    // 选择图片
    handleSelectImage(item) {
      if (!vm.selectedImg) {
        vm.selectedPosition = null;
        vm.selectedImg = item;
        vm.choseImg = item;
        vm.canvas.defaultCursor = "crosshair";
        vm.canvas.hoverCursor = "crosshair";
      } else {
        vm.selectedImg = null;
        vm.choseImg = {};
        vm.canvas.defaultCursor = "default";
        vm.canvas.hoverCursor = "default";
      }
    },
    handleSelectValue(value) {
      vm.selectValue = value;
      vm.positionImg = vm.imgArr.find((item) => {
        return item.modelId == value;
      });
      // console.log(vm.positionImg, "positionImg");
    },
    handleSelectItemValue(item, value) {
      // 1.将对应的allObjects内的该对象（item）的imgtarget更新到最新选择
      const newImgTarget = vm.imgArr.find((img) => img.modelId === value);
      if (newImgTarget) {
        vm.$set(item, "imgtarget", newImgTarget); // 使用 $set 更新
      }
      // 2.更新对应的画布中的对象的图片然后重新渲染画布，保证修改后的allObjects中的该对象和画布上的对象对应
      if (item.fabricObject) {
        // 加载新图片
        vm.wayLoadImage(newImgTarget.imageUrl).then((img) => {
          // 保存原对象的位置和角度
          const originalLeft = item.fabricObject.get("left");
          const originalTop = item.fabricObject.get("top");
          const originalAngle = item.fabricObject.get("angle");
          // 移除旧的 fabricObject
          vm.canvas.remove(item.fabricObject);
          // 创建新的 fabric.Image 对象
          const originalWidth = newImgTarget.w;
          const originalHeight = newImgTarget.h;
          // const originalWidth = img.width;
          // const originalHeight = img.height;
          const displayWidth = originalWidth * vm.rate;
          const displayHeight = originalHeight * vm.rate;
          const newFabricImg = vm.constructionFabricImage(
            img,
            originalLeft,
            originalTop,
            displayWidth / originalWidth,
            displayHeight / originalHeight,
            originalAngle,
            newImgTarget.modelId,
            newImgTarget.imageUrl
          );
          // 添加新的 fabricObject 到画布
          vm.canvas.add(newFabricImg);
          // 设置选中状态
          vm.canvas.setActiveObject(newFabricImg);
          // 更新 allObjects 中的 fabricObject 引用
          item.fabricObject = newFabricImg;
          // 更新文字位置和角度
          if (item.textObject) {
            item.textObject.set({
              left: originalLeft,
              top: originalTop,
              angle: originalAngle,
            });
            item.textObject.visible = vm.isTextVisible;
          }
          // 更新箭头位置和角度
          if (item.arrowObject) {
            vm.updateArrowAndBorderPosition(newFabricImg);
          }
          // 画布渲染
          // vm.canvas.requestRenderAll();
          vm.throttledRender();
        });
      }
    },
    handleSelectItemValue2(item, value) {
      // 更新对应对象的 type 属性
      vm.$message({
        message: "选择成功！",
        type: "success",
      });
      item.type = value;
    },
    // 选择业务点位
    handleSelectPosition(item) {
      if (!vm.selectValue) {
        vm.$message({
          message: "请先在上方下拉框选择模型！",
          type: "warning",
        });
        return;
      }
      if (!vm.selectedPosition) {
        vm.selectedPosition = item;
        vm.selectedImg = null;
        vm.choseImg = {};
        vm.canvas.defaultCursor = "crosshair";
        vm.canvas.hoverCursor = "crosshair";
      } else {
        vm.selectedPosition = null;
        vm.canvas.defaultCursor = "default";
        vm.canvas.hoverCursor = "default";
      }
    },
    // 过滤业务列表
    handleFiltrate(value) {
      vm.filtrate = value;
      console.log(value, "value");
      vm.requestpositionMsg(value);
      let params = {};
      if (value.preferType) {
        params.preferTypes = [...value.preferType];
        vm.requestgetModel(params, "business");
      }
      // vm.filteredPositionMsgArr = vm.positionMsgArr.filter((item) => {
      //   // 确保 item.posName 是一个字符串，如果不是，则将其转换为字符串或直接返回 false
      //   const posName = item.posName || "";
      //   return posName.includes(value);
      // });
    },
    // 处理对象修改事件
    handleObjectModified(options) {
      const object = options.target; // 获取被修改的对象
      // object.isDirty = true; // 标记为脏对象
      const canvas = vm.canvas;
      // 获取对象的最新位置（中心点）
      const posX = object.get("left");
      const posY = object.get("top");
      // 获取对象的宽度和高度
      // const width = object.get("width");
      // const height = object.get("height");
      const width = object.getScaledWidth();
      const height = object.getScaledHeight();
      // 获取对象的旋转角度
      const angle = object.get("angle");
      // 更新choseObj为当前选中的对象
      vm.choseObj = vm.allObjects.find((obj) => obj.fabricObject === object);
      // console.log(vm.choseObj, "vm.choseObj");
      // 如果需要更新choseObj的最新位置和角度
      if (vm.choseObj && vm.choseObj.fabricObject === object) {
        vm.show3 = true; // 显示选中对象区域
        vm.choseObj.x = keepDecimal(posX, vm.dig, 1);
        vm.choseObj.y = keepDecimal(posY, vm.dig, 1);
        vm.choseObj.width = keepDecimal(width, vm.dig, 1);
        vm.choseObj.height = keepDecimal(height, vm.dig, 1);
        vm.choseObj.angle = keepDecimal(angle, vm.dig, 1);
        // 更新文字位置和角度
        if (vm.choseObj.textObject) {
          vm.choseObj.textObject.set({
            left: keepDecimal(posX, vm.dig, 1),
            top: keepDecimal(posY, vm.dig, 1),
            angle: keepDecimal(angle, vm.dig, 1),
          });
          vm.choseObj.textObject.visible = vm.isTextVisible;
          canvas.requestRenderAll();
        }
        // 更新箭头和框体位置和角度
        if (vm.choseObj.arrowObject || vm.choseObj.borderObject) {
          // 更新边框大小
          if (vm.choseObj.borderObject) {
            vm.choseObj.borderObject.set({
              width: width + vm.borderAndpadding,
              height: height + vm.borderAndpadding,
              left: posX,
              top: posY,
              angle: angle,
            });
          }
          // 更新箭头位置
          vm.updateArrowAndBorderPosition(object);
        }
        console.log(vm.choseObj, "vm.choseObj");
      }
    },
    // 处理对象选中事件
    handleObjectSelected(options) {
      const selectedObjects = options.selected;
      if (selectedObjects && selectedObjects.length > 0) {
        const object = selectedObjects[0];
        // 遍历allObjects找到对应的对象
        vm.allObjects.forEach((obj, index) => {
          if (obj.fabricObject === object) {
            // 隐藏关联文字和箭头
            if (obj.textObject) {
              obj.textObject.visible = false;
            }
            if (obj.arrowObject) {
              obj.arrowObject.visible = vm.isArrowVisible;
            }
            if (obj.borderObject) {
              obj.borderObject.visible = vm.isBorderVisible;
            }
            // vm.canvas.requestRenderAll();
            vm.throttledRender();
            // 标记为选中状态
            vm.$set(vm.allObjects[index], "isSelected", true);
            vm.show3 = true; // 显示选中对象区域
            // 调用positionList组件的方法，滚动到对应的DOM节点
            // vm.$refs.positionList.scrollToItem(index);
          } else {
            // 取消其他对象的选中状态和文字、箭头显示
            if (obj.textObject) {
              obj.textObject.visible = vm.isTextVisible;
            }
            if (obj.arrowObject) {
              obj.arrowObject.visible = vm.isArrowVisible;
            }
            if (obj.borderObject) {
              obj.borderObject.visible = vm.isBorderVisible;
            }
            vm.$set(vm.allObjects[index], "isSelected", false);
          }
        });
      }
    },
    // 处理对象取消选中事件
    handleObjectDeselected(options) {
      // 遍历allObjects恢复所有文字的可见性并清除选中状态
      vm.allObjects.forEach((obj, index) => {
        if (obj.textObject) {
          obj.textObject.visible = vm.isTextVisible;
        }
        if (obj.arrowObject) {
          obj.arrowObject.visible = vm.isArrowVisible;
        }
        vm.$set(vm.allObjects[index], "isSelected", false);
      });
      // vm.canvas.requestRenderAll();
      vm.throttledRender();
      vm.choseObj = null; // 取消选中时重置choseObj
      vm.show3 = false; // 隐藏选中对象区域
    },
    // 键盘事件处理
    handleKeyDown(event) {
      if (event.key === "Delete") {
        const activeObject = vm.canvas.getActiveObject();
        if (activeObject) {
          vm.deleteSelectedObject(activeObject);
        }
      }
    },
    handleChoseitem(index) {
      // 选中vm.allObjects指定索引值的对象，更改对象的选中状态（注：同时其他对象置为非选中），切让画布中的对应对象处于选中状态
      // 获取指定索引的对象
      const selectedObj = vm.allObjects[index];
      // 检查对象是否存在
      if (!selectedObj) return;
      // 设置画布的活动对象（触发 Fabric.js 的 selection:created 事件）
      vm.canvas.setActiveObject(selectedObj.fabricObject);
      // 可选：手动触发对象选中事件（如果自动触发未生效）
      // vm.handleObjectSelected({ selected: [selectedObj.fabricObject] });
      // 刷新画布
      vm.updateAllObjectsCoords();
      // vm.canvas.requestRenderAll();
      vm.throttledRender();
    },
    // 删除对象（索引值索引）
    deleteObject(index) {
      const obj = vm.allObjects[index];
      vm.canvas.remove(obj.fabricObject);
      if (obj.textObject) {
        vm.canvas.remove(obj.textObject);
      }
      if (obj.arrowObject) {
        vm.canvas.remove(obj.arrowObject);
      }
      if (obj.borderObject) {
        vm.canvas.remove(obj.borderObject);
      }
      vm.allObjects.splice(index, 1);
      // console.log(obj, "objobjobj");
      // 如果是业务对象则添加回列表（成为点位保存以后就是业务信息了）
      if (obj.posId) {
        if (obj.targetObj) {
          vm.addBusinessItem(obj.targetObj);
        } else if (obj.pointObject) {
          let backObj = {
            config: obj.pointObject?.config ?? "",
            createTime: obj.pointObject?.createTime ?? "",
            createUser: obj.pointObject?.createUser ?? "",
            posId: obj.pointObject.posId,
            posName: obj.pointObject?.posName ?? "",
            posNo: obj.pointObject.posNo,
            subType: obj.pointObject.subType,
            tenant: obj.pointObject.tenant,
            type: obj.pointObject.type,
            updateTime: obj.pointObject.updateTime,
            updateUser: obj.pointObject.updateUser,
            version: obj.pointObject.version,
          };
          vm.addBusinessItem(backObj);
        }
      }
      // vm.canvas.requestRenderAll();
      vm.throttledRender();
    },
    // 删除选中对象（对象索引）
    deleteSelectedObject(object) {
      const index = vm.allObjects.findIndex(
        (obj) => obj.fabricObject === object
      );
      const foundItem = vm.allObjects.find(
        (item) => item.fabricObject === object
      );
      if (index !== -1) {
        const selectedItem = vm.allObjects[index];
        vm.canvas.remove(selectedItem.fabricObject);
        // 移除关联对象
        if (selectedItem.textObject) {
          vm.canvas.remove(selectedItem.textObject);
          selectedItem.textObject.off();
        }
        if (selectedItem.arrowObject) {
          vm.canvas.remove(selectedItem.arrowObject);
          selectedItem.arrowObject.off();
        }
        if (selectedItem.borderObject) {
          vm.canvas.remove(selectedItem.borderObject);
          selectedItem.borderObject.off();
        }
        // 从数组中移除
        vm.allObjects.splice(index, 1);
        // 重置选中状态
        if (vm.choseObj === selectedItem) {
          vm.choseObj = null;
          vm.show3 = false;
        }
        // 如果是业务对象则添加回列表（成为点位保持以后就是业务信息了）
        if (foundItem.posId) {
          if (foundItem.targetObj) {
            vm.addBusinessItem(foundItem.targetObj);
          } else if (foundItem.pointObject) {
            let backObj = {
              config: foundItem.pointObject.config,
              createTime: foundItem.pointObject.createTime,
              createUser: foundItem.pointObject.createUser,
              posId: foundItem.pointObject.posId,
              posName: foundItem.pointObject.posName,
              posNo: foundItem.pointObject.posNo,
              subType: foundItem.pointObject.subType,
              tenant: foundItem.pointObject.tenant,
              type: foundItem.pointObject.type,
              updateTime: foundItem.pointObject.updateTime,
              updateUser: foundItem.pointObject.updateUser,
              version: foundItem.pointObject.version,
            };
            vm.addBusinessItem(backObj);
          }
        }
        // 强制垃圾回收
        if (typeof gc === "function") gc();
        // vm.canvas.requestRenderAll();
        vm.throttledRender();
      }
    },
    // 业务对象绘制成功后将对应的显示的业务列表中的项删除刷新
    deleteBusinessItem() {
      // const flage = vm.selectedPosition.posId;
      // vm.positionMsgArr = vm.positionMsgArr.filter(
      //   (item) => item.posId !== flage
      // );
      // vm.filterPositionMsgArr()
      // vm.handleFiltrate(vm.filtrate);
      vm.requestpositionMsg(vm.filtrate);
    },
    // 删除对象列表中的业务对象时要把对应的业务对象添加回去
    addBusinessItem(obj) {
      // vm.positionMsgArr.push(obj);
      // vm.filterPositionMsgArr()
      // vm.handleFiltrate(vm.filtrate);
      vm.requestpositionMsg(vm.filtrate);
    },
    // 筛选positionMsgArr
    filterPositionMsgArr() {
      // 对比positionMsgArr和allObjects，删除positionMsgArr中在allObjects中的项（根据posId），返回新的数组
      const newPositionMsgArr = vm.positionMsgArr.filter(
        (item) =>
          !vm.allObjects.some((obj) => {
            // 仅当 obj.posId 存在时才进行比较
            if (obj.posId) {
              return obj.posId === item.posId;
            }
            return false;
          })
      );
      vm.filteredPositionMsgArr = newPositionMsgArr;
    }
  };
}
